package com.rtx.wms.std.so.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rtx.api.annotation.DataSourceAnnotation;
import com.rtx.common.EdiBeanUtils;
import com.rtx.edi.model.api.bo.ApiMappingInfoBo;
import com.rtx.model.dto.edi.EdiInnerRequestDTO;
import com.rtx.wms.std.common.bean.WmsConstant;
import com.rtx.wms.std.ctclass.ClassHolder;
import com.rtx.wms.std.sku.bean.po.Sku;
import com.rtx.wms.std.so.bean.ApiOrderdetail;
import com.rtx.wms.std.so.bean.ApiOrders;
import com.rtx.wms.std.so.mapper.ApiOrderdetailMapper;
import com.rtx.wms.std.so.mapper.ApiOrdersMapper;
import com.rtx.wms.std.so.mapper.dymapper.DyApiOrderdetailMapper;
import com.rtx.wms.std.so.service.ApiOrdersService;

import cn.hutool.core.util.IdUtil;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wq
 * @since 2023-04-14
 */
@Service
public class ApiOrdersServiceImpl extends ServiceImpl<ApiOrdersMapper, ApiOrders> implements ApiOrdersService {

    @Autowired
    private ApiOrderdetailMapper apiOrderdetailMapper;
    
    @Autowired
    DyApiOrderdetailMapper dyApiOrderdetailMapper;
    

    @DataSourceAnnotation
    @Override
    public void addApiOrders(String whseid, ApiOrders apiOrders,EdiInnerRequestDTO dto) {
        String batchid = IdUtil.getSnowflakeNextIdStr();
        int line = 1;
        
        //是否使用 动态加载字段拼接sql
        boolean activeConfig = false;
        //获取edi 配置
        ApiMappingInfoBo config =  Optional.ofNullable(dto.getConfig()).orElse(new ApiMappingInfoBo()) ;
        //获取生效的目标apiid，就是当前需要被调用的restapi
        Long targetid = config.getTargetApi().getId();
        //获取启动或者被被更新时候动态创建的实体类
        Map<String,Class> map = ClassHolder.apiconfigClassMap.get(targetid+"");
        //假如动态创建的类存在则 通过调用通过反射获取bean对象属性拼接sql的方法
        if(map != null) {
        	activeConfig = true;
        }
        
        for(ApiOrderdetail apiOrderdetail : apiOrders.getDetails()){
            apiOrderdetail.setBatchid(batchid);
            apiOrderdetail.setOrderlinenumber(String.format("%05d",line++));
            if(activeConfig) {
            	//调用通过反射获取bean对象属性拼接sql的方法做插入
            	dyApiOrderdetailMapper.rtxconfigColumnsSave(apiOrderdetail);
            }else {
            	apiOrderdetailMapper.insert(apiOrderdetail);
            }
        }
        apiOrders.setBatchid(batchid);
        apiOrders.setEdiflag(WmsConstant.DEFAULT_FLAG);
        apiOrders.setRtxqueue(0);
        if(activeConfig) {
        	//调用通过反射获取bean对象属性拼接sql的方法做插入
        	dyApiOrderdetailMapper.rtxconfigColumnsSave(apiOrders);
        }else {
        	baseMapper.insert(apiOrders);
        }
    }

    @DataSourceAnnotation
    @Override
    public List<ApiOrders> selectApiOrdersByWrapper(String whseid, Wrapper<ApiOrders> wrapper,ApiMappingInfoBo bo) {
        List<ApiOrders> ordersList = convertToConfigApiOrders(bo,(QueryWrapper<ApiOrders>) wrapper);
        for(ApiOrders o : ordersList){
            QueryWrapper<ApiOrderdetail> detailQuery = Wrappers.query();
            detailQuery.eq("batchid",o.getBatchid());
            List<ApiOrderdetail> details = convertToConfigApiOrderdetail(bo,(QueryWrapper<ApiOrderdetail>)detailQuery);
            o.setDetails(details);
        }
        return ordersList;
    }
    
    //获取有新增字段的对象
    private List<ApiOrders> convertToConfigApiOrders(ApiMappingInfoBo bo,QueryWrapper<ApiOrders> qw){
    	List<ApiOrders> head = new ArrayList<>();
    	try {
    		String apiid =  bo.getTargetApi().getId()+"";
    		Map<String,Class> map = ClassHolder.apiconfigClassMap.get(apiid);

    		if(map != null && map.get("main") != null) {
    			Class headclass = map.get("main");
    			qw.select(EdiBeanUtils.getCoulmns(headclass));
    			List<Map<String, Object>> oriData = baseMapper.selectMaps(qw);
    			for(Map<String, Object> dataMap:oriData) {
    				ApiOrders o =(ApiOrders) EdiBeanUtils.copyFields(dataMap, headclass);
    				head.add(o);
    			}
    		}else {
    			head = baseMapper.selectList(qw);
    		}
    	} catch (Exception e) {
    		head = baseMapper.selectList(qw);
    	}

    	return head;
    }
    
    //获取有新增字段的对象
    private List<ApiOrderdetail> convertToConfigApiOrderdetail(ApiMappingInfoBo bo,QueryWrapper<ApiOrderdetail> qw){
    	List<ApiOrderdetail> head = new ArrayList<>();
    	try {
    		String apiid =  bo.getTargetApi().getId()+"";
    		Map<String,Class> map = ClassHolder.apiconfigClassMap.get(apiid);

    		if(map != null && map.get("sub") != null) {
    			Class detailclass = map.get("sub");
    			qw.select(EdiBeanUtils.getCoulmns(detailclass));
    			List<Map<String, Object>> oriData = apiOrderdetailMapper.selectMaps(qw);
    			for(Map<String, Object> dataMap:oriData) {
    				ApiOrderdetail o =(ApiOrderdetail) EdiBeanUtils.copyFields(dataMap, detailclass);
    				head.add(o);
    			}
    		}else {
    			head = apiOrderdetailMapper.selectList(qw);
    		}
    	} catch (Exception e) {
    		head = apiOrderdetailMapper.selectList(qw);
    	}

    	return head;
    }

    @DataSourceAnnotation
    @Override
    public void updateByWrapper(String whseid,LambdaUpdateWrapper<ApiOrders> update) {
        baseMapper.update(null,update);
    }

    @Transactional
    @DataSourceAnnotation
	@Override
	public void deleteApiOrders(String whseid, ApiOrders apiOrders) {
    	
        LambdaUpdateWrapper<ApiOrderdetail> upd = Wrappers.lambdaUpdate();
        upd.eq(ApiOrderdetail::getBatchid, apiOrders.getBatchid());
        apiOrderdetailMapper.delete(upd);
        
        LambdaUpdateWrapper<ApiOrders> aupd =Wrappers.lambdaUpdate();
        aupd.eq(ApiOrders::getBatchid, apiOrders.getBatchid());
        baseMapper.delete(aupd);
	}

    @DataSourceAnnotation
	@Override
	public List<ApiOrders> selectApiOrdersByWrapperNoDetail(String whseid, Wrapper<ApiOrders> wrapper) {
		return baseMapper.selectList(wrapper);
	}
    
    
}
